package com.congwulin.wechat.util.interfaces;

import com.congwulin.wechat.entity.common.SuperVO;
import com.congwulin.wechat.util.SpringUtil;
import com.congwulin.wechat.util.VOTsCheck;
import com.congwulin.wechat.util.service.RedisLockService;
import com.congwulin.wechat.util.service.vo.VODeleteService;
import com.congwulin.wechat.util.service.vo.VOPersistent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public abstract class AbstractVOService {
    private static final Logger Log = LoggerFactory.getLogger(VODeleteService.class);
    /**
     * 实体保存数据库器
     */
    private VOPersistent dao;

    /**
     * 实体抽象服务构造函数
     *
     * @param dao 实体保存数据库器
     */
    public AbstractVOService(VOPersistent dao) {
        this.dao = dao;
    }

    /**
     * 检查对应实体的时间戳和数据库是否一致
     *
     * @param list 实体列表
     */
    protected void checkTs(List<SuperVO> list) {
        VOTsCheck checker = new VOTsCheck();
        int size = list.size();
        SuperVO[] vos = new SuperVO[size];
        vos = list.toArray(vos);
        if (size > 0) {
            checker.check(vos, vos[0].getTableName());
        }
    }

    /**
     * 获取实体数据库保存器
     *
     * @return 实体数据库保存器
     */
    protected VOPersistent getDAO() {
        return this.dao;
    }

    /**
     * 对实体列表进行加锁
     *
     * @param list  实体类和实体列表的映射
     */
    protected Map<String,String> lock(List<SuperVO> list) {
        RedisLockService lock = SpringUtil.getBean(RedisLockService.class);
        List<String> ids = new ArrayList<String>();
        for(SuperVO vo:list){
            ids.add(vo.getId());
        }
        return lock.lockWithTimeout(ids.toArray(new String[0]),2000L,2000L);
    }

    /**
     * 对实体列表进行解锁
     *
     * @param lockname  分布式锁名称的映射
     */
    protected boolean unlock(Map<String,String> lockname) {
        RedisLockService lock = SpringUtil.getBean(RedisLockService.class);
        boolean flag = lock.releaseLock(lockname);
        return flag;
    }
}
